/**
 * 
 */
package org.startup.service.impl;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URISyntaxException;
import java.util.List;

import org.startup.domain.Customer;
import org.startup.service.CustomerService;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * @author asudar
 * 
 */
public class CustomerServiceImpl extends ServiceImpl implements CustomerService {

	private List<Customer> customerList;
	private static CustomerServiceImpl customerServiceImpl = new CustomerServiceImpl();

	private CustomerServiceImpl() {
	}

	/**
	 * @param customerList
	 *            the customerList to set
	 */
	public void setCustomerList(List<Customer> customerList) {
		this.customerList = customerList;
	}

	public void create(Customer customer) {

	}

	public List<Customer> getAll() {
		readCustomersFromFile();
		return customerList;
	}

	public Customer findBy(Long id) {
		List<Customer> customerList = getAll();

		for (int i = 0; i < customerList.size(); i++) {
			Customer customer = customerList.get(i);

			if (customer.getId().equals(id)) {
				return customer;
			}
		}

		return null;
	}

	public Customer findBy(String email) {
		List<Customer> customerList = getAll();

		for (int i = 0; i < customerList.size(); i++) {
			Customer customer = customerList.get(i);

			if (customer.getEmail().equals(email)) {
				return customer;
			}
		}

		return null;
	}

	private void readCustomersFromFile() {
		List<Customer> customerList = null;
		InputStream inputStream = null;
		try {
			File jsonFile = new File(this.getClass()
					.getResource("/customers.json").toURI());

			inputStream = new FileInputStream(jsonFile);
			ObjectMapper objectMapper = new ObjectMapper();
			customerList = objectMapper.readValue(inputStream,
					new TypeReference<List<Customer>>() {
					});

		} catch (IOException e) {
			e.printStackTrace();
		} catch (URISyntaxException e) {
			e.printStackTrace();
		}

		setCustomerList(customerList);
	}

	public static CustomerService getInstance() {
		return customerServiceImpl;
	}

}
